package com.kim.controller;

import com.kim.pojo.Result;
import com.kim.pojo.User;
import com.kim.service.UserService;
import com.kim.utils.JwtUtil;
import com.kim.utils.Md5Util;
import com.kim.utils.ThreadLocalUtil;
import jakarta.validation.constraints.Pattern;
import lombok.RequiredArgsConstructor;
import org.hibernate.validator.constraints.URL;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Validated
@RequiredArgsConstructor
public class UserController {

    private final  UserService userService;

    private final StringRedisTemplate stringRedisTemplate;

    @PostMapping("/register")
    public Result register(@Pattern(regexp = "^\\S{3,16}$") String username, @Pattern(regexp = "^\\S{6,20}$") String password) {
        //参数校验
        //用户名校验
        /*String usernameRegex = "^[a-zA-Z0-9_]{3,16}$";
        Pattern pattern = Pattern.compile(usernameRegex);
        Matcher matcher = pattern.matcher(username);
        if (!matcher.matches()) {
            return Result.error("用户名不符合规则[3-16的字母数字以及下划线]");
        }
        String passwordRegex = "^[a-zA-Z0-9_]{6,20}$";
        pattern = Pattern.compile(passwordRegex);
        matcher = pattern.matcher(password);
        if (!matcher.matches()) {
            return Result.error("密码不符合规则[6-20的字母数字以及下划线]");
        }*/
        //查询用户
        User user = userService.findByUsername(username);
        if (user == null) {
            //没有占用
            //注册
            userService.register(username,password);
            return Result.success();
        }else {
            //占用
            return Result.error("用户名已被占用;请重新输入");
        }
    }

    //登录
    @PostMapping("/login")
    public Result login(@Pattern(regexp = "^\\S{3,16}$") String username,@Pattern(regexp = "^\\S{6,20}$") String password){
        //根据用户名查询用户
        User user = userService.findByUsername(username);
        //判断是否存在
        if(user == null){
            return Result.error("用户名不存在，需注册");
        }
        //判断密码是否正确 user对象中的password是密文
        if(Md5Util.getMD5String(password).equals(user.getPassword())){
            //登录成功
            HashMap<String, Object> claims = new HashMap<>();
            claims.put("id",user.getId());
            claims.put("username",user.getUsername());
            String token = JwtUtil.genToken(claims);
            //将token存储到redis中
            stringRedisTemplate.opsForValue().set(token,token,1, TimeUnit.HOURS);
            return Result.success(token);
        }else {
            return Result.error("密码不正确，请重新输入");
        }
    }

    @GetMapping("/userInfo")
    //根据请求头查询用户信息
    public Result<User> userInfo(/*@RequestHeader(name = "Authorization")*/String token){
        //根据用户名查询用户id
        /*Map<String, Object> claims = JwtUtil.parseToken(token);
        String username =(String)claims.get("username");*/
        Map<String,Object> userMap = ThreadLocalUtil.get();
        String username = (String) userMap.get("username");
        User user = userService.findByUsername(username);
        return Result.success(user);
    }

    @PutMapping("/update")
    public Result update(@RequestBody @Validated User user){
        userService.update(user);
        return Result.success();
    }

    //更新用户头像
    @PatchMapping("updateAvatar")
    public Result updateAvatar(@RequestParam @URL String avatarUrl){
        userService.updateAvatar(avatarUrl);
        return Result.success();
    }

    //更新用户密码
    @PatchMapping("/updatePwd") //只更新一个信息，所以用Patch
    public Result updatePwd(@RequestBody Map<String,String> params,@RequestHeader("Authorization")String token){
        //1.校验参数
        String oldPwd = params.get("old_pwd");
        String newPwd = params.get("new_pwd");
        String rePwd = params.get("re_pwd");
        if (!StringUtils.hasLength(oldPwd)||!StringUtils.hasLength(newPwd)||!StringUtils.hasLength(rePwd)){
            return Result.error("缺少必要的参数");
        }
        //原密码是否正确
        //调用userService根据用户名拿到原密码，再和old_pwd对比
        Map<String,Object> claims = ThreadLocalUtil.get();
        String username =(String) claims.get("username");
        User user = userService.findByUsername(username);
        if(!user.getPassword().equals(Md5Util.getMD5String(oldPwd))){
            return Result.error("原密码填写不正确");
        }
        //校验新密码和确认密码是否一样
        if(!rePwd.equals(newPwd)){
            return Result.error("两次填写的密码不一致");
        }
        //2.调用service完成密码更新
        userService.setNewPwd(newPwd);
        //更新密码成功后要删除对应的token
        stringRedisTemplate.opsForValue().getOperations().delete(token);
        return Result.success();
    }
}
